<template>
    <!-- 嵌入app的上传 目前仅支持图片 2022.08.25 -->
    <div
        class="app-upload"
        @click="handleAppUpload"
        :maxCount="defaultMaxCount"
    >
        <slot>
            <van-button icon="plus" type="primary">上传文件</van-button>
        </slot>
    </div>
    <van-action-sheet
        v-model:show="showAction"
        :actions="actionsList"
        :multiple="multiple"
        @select="onSelect"
        @cancel="showAction = false"
    />
</template>

<script setup>
import { ref, onMounted, defineEmits, defineProps, computed } from 'vue';
import { useStore } from 'vuex';

const props = defineProps({
    // 限制上传的文件大小
    acceptSize: {
        type: Number,
        default: Infinity
    },
    // 文件上传数量限制
    maxCount: {
        type: Number,
        default: Infinity
    },
    // 是否开启图片多选，部分安卓机型不支持
    multiple: {
        type: Boolean,
        default: false
    }
});
const emit = defineEmits(['on-app-success']);

const store = useStore();

const brandInfo = computed(() => {
    return store.state.brand?.publishBrand;
})

const defaultMaxCount = computed(() => {
    if (props.multiple) {
        return props.maxCount;
    } else {
        return 1;
    }
});
const actionsList = ref([
    { name: '拍照', type: 'camera' },
    { name: '从相册选择', type: 'album' }
]);
const showAction = ref(false);
const materList = ref([]);

const onSelect = (selectItem) => {
    let materLen = materList.value.length || 0;
    let len = defaultMaxCount.value - materLen;

    if (defaultMaxCount.value && len === 0) {
        G_dispatchEvent('toast', { message: `抱歉，最多只能上传${defaultMaxCount.value}个文件奥~`, type: 'error'});
        return;
    }
    console.log('dtBrandId', brandInfo.value, brandInfo.value.brand)
    store
        .dispatch('jsBridge/SXYJSBridge', {
            method: 'openAlbum',
            fun: selectItem.type, //  上传类型
            data: {
                dtBrandId: brandInfo.value.brand,
                max: selectItem.type === 'album' ? defaultMaxCount.value : 1
            },
            callback: (data) => {
                console.log('appdata', data)
                emit('on-app-success', data.materials);
            }
        })
        .then(() => {
            showAction.value = false;
        });
};

const handleAppUpload = () => {
    showAction.value = true;
};
onMounted(() => {});
</script>

<style lang="scss" scoped></style>
